import { createApp } from 'vue';
import { createPinia } from 'pinia';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import './style.css'
import App from './App.vue'
import router from './router'
import { validateToken, setupAxiosInterceptors } from './utils/auth-utils'
import { ElMessage } from 'element-plus'
import moment from 'moment'

// 全局WebSocket连接
let socket: WebSocket | null = null;

export const connectWebSocket = (userId: number): Promise<void> => {
  return new Promise((resolve, reject) => {
    // 关闭已有连接
    if (socket) {
      socket.close();
      console.log(`[${new Date().toLocaleString()}] [INFO] 已关闭现有WebSocket连接`);
    }

    // 创建新连接 - 修正连接路径为根路径
    // 从环境变量获取WebSocket主机，默认为localhost:5000
    const wsHost = import.meta.env.VITE_WS_HOST || 'localhost:5000';
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${wsHost}/`;
    console.log(`[${new Date().toLocaleString()}] [INFO] 尝试建立WebSocket连接: ${wsUrl}`);
    socket = new WebSocket(wsUrl);

    socket.onopen = () => {
      console.log(`[${new Date().toLocaleString()}] [INFO] WebSocket连接已建立: ${wsUrl}`);
      // 修正发送数据格式，与后端期望的格式匹配
      const loginData = JSON.stringify({ type: 'login', data: { userId } });
      console.log(`[${new Date().toLocaleString()}] [INFO] 发送登录数据: ${loginData}`);
      socket?.send(loginData);
      resolve(); // 连接成功，解决Promise
    };

    socket.onclose = (event) => {
      console.log(`[${new Date().toLocaleString()}] [INFO] WebSocket连接已关闭，代码: ${event.code}, 原因: ${event.reason}`);
      reject(new Error(`WebSocket连接已关闭: ${event.code} - ${event.reason}`));
    };

    socket.onerror = (error) => {
      const errorMsg = error instanceof Error ? error.message : String(error);
      console.error(`[${new Date().toLocaleString()}] [ERROR] WebSocket错误:`, errorMsg);
      ElMessage.error(`WebSocket连接失败: ${errorMsg}`);
      reject(new Error(`WebSocket连接失败: ${errorMsg}`));
    };
  });
};

export const getSocket = () => socket;

const app = createApp(App)
const pinia = createPinia();
app.use(pinia);

// 设置axios拦截器
setupAxiosInterceptors()

// 应用初始化时验证token
async function initApp() {
  const token = localStorage.getItem('token')
  if (token) {
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [应用初始化] 发现token，开始验证有效性`)
    const isValid = await validateToken()
    if (!isValid) {
      ElMessage.warning('登录状态已失效，请重新登录')
    }
  } else {
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [应用初始化] 未发现token`)
  }

  // 挂载应用
  app.use(router)
  app.use(ElementPlus)
  
  // 全局属性
  app.config.globalProperties.$connectWebSocket = connectWebSocket;
  app.config.globalProperties.$getSocket = getSocket;
  
  app.mount('#app')
}

// 执行初始化
initApp()
